//
//  Classify.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/10.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import Foundation
import SwiftyJSON
import Alamofire


struct Classify {
    var name: String
    var classId: Int
    
    init(name: String, classId: Int) {
        self.name = name
        self.classId = classId
    }
}

enum ClassifyRequest: RequestProtocol {
    var host: String {
        return "http://120.25.176.231:8000/seller-material/material/"
    }
    case newClassification(name: String)
    case editClassification(name: String, id: Int)
    case allClassifications()

    case deleteClass(id: Int)
    
    case newCategory(parent: Int, name: String)
    case allCategories(id: Int)
    //case allMaterials()
    
    var path: String {
        switch self {
        case .newClassification(_):
            return "class/create"
        case .editClassification(_, _):
            return "class/edit"
        case .allClassifications():
            return "class/find"
        case .deleteClass(_):
            return "class/delete"
        case .newCategory(_, _):
            return "class/create"
        case .allCategories(_):
            return "class/findchildren"
        }
    }
    
    var bodyParams: Parameters {
        switch self {
        case .newClassification(let name):
            return ["name": name, "storeId": Store.storeId!, "sessionId": Store.sessionID!]
        case .editClassification(let name, let id):
            return ["name": name, "sessionId": Store.sessionID!, "storeId": Store.storeId!, "classId": id]
        case .allClassifications():
            return ["sessionId": Store.sessionID!, "storeId": Store.storeId!]
        case .deleteClass(let id):
            return ["sessionId": Store.sessionID!, "storeId": Store.storeId!, "classId": id]
        case .newCategory(let parent, let name):
            return ["sessionId": Store.sessionID!, "storeId": Store.storeId!, "name": name, "parentClassId": parent]
        case .allCategories(let id):
            return ["sessionId": Store.sessionID!, "storeId": Store.storeId!, "classId": id]
        }
    }
    
    var fullURL: URL {
        let str = self.host + self.path
        return URL(string: str)!
    }
}

class ClassifyVCHelper {
    var request: ClassifyRequest = .allClassifications()
    func dataRequest(from request: ClassifyRequest) -> DataRequest {
        //return Alamofire.request(request.fullURL, method: .post, parameters: request.bodyParams, encoding: URLEncoding.httpbody)
        return Alamofire.request(request.fullURL, method: request.method, parameters: request.bodyParams, encoding: URLEncoding.httpBody, headers: nil)
        //return Alamofire.request(request.fullURL, method: request.method, parameters: request.bodyParams, encoding: URLEncoding.httpbody, headers: nil)
    }
    
    func newClassification(name: String, completeHandler: @escaping (Bool, Classify?) -> Void) {
        request = .newClassification(name: name)
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false, nil)
                }
                return
            }
            let json = JSON(result)
            if json["status"].intValue == 200 {
                let classId = json["data"]["classId"].intValue
                let classify = Classify(name: name, classId: classId)
                DispatchQueue.main.async {
                    completeHandler(true, classify)
                }
            } else {
                DispatchQueue.main.async {
                    completeHandler(false, nil)
                }
            }
        }
    }
    func editClassification(name: String, id: Int, completeHandler: @escaping (Bool) -> Void) {
        request = .editClassification(name: name, id: id)
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
                return
            }
            let json = JSON(result)
            if json["status"].intValue == 200 {
                DispatchQueue.main.async {
                    completeHandler(true)
                }
            } else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
            }
        }
    }
    func allClassifications(completeHandler: @escaping (Bool, [Classify]?) -> Void) {
        request = .allClassifications()
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false, nil)
                }
                return
            }
            let json = JSON(result)
            if json["status"].intValue == 200 {
                let data = json["data"].arrayValue
                var classifications = [Classify]()
                for item in data {
                    let classId = item["classId"].intValue
                    let name = item["name"].stringValue
                    let classification = Classify(name: name, classId: classId)
                    classifications.append(classification)
                }
                DispatchQueue.main.async {
                    completeHandler(true, classifications)
                }
            } else {
                DispatchQueue.main.async {
                    completeHandler(false, nil)
                }
            }
        }
    }
    func deleteClass(id: Int, completeHandler: @escaping (Bool) -> Void) {
        request = .deleteClass(id: id)
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
                return
            }
            let json = JSON(result)
            if json["status"].intValue == 200 {
                DispatchQueue.main.async {
                    completeHandler(true)
                }
            } else {
                DispatchQueue.main.async {
                    completeHandler(false)
                }
            }
        }
    }
    func newCategory(name: String, parent: Int, completeHandler: @escaping (Bool, Classify?) -> Void) {
        request = .newCategory(parent: parent, name: name)
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false, nil)
                }
                return
            }
            let json = JSON(result)
            if json["status"].intValue == 200 {
                let classId = json["data"]["classId"].intValue
                let classification = Classify(name: name, classId: classId)
                DispatchQueue.main.async {
                    completeHandler(true, classification)
                }
            } else {
                DispatchQueue.main.async {
                    completeHandler(false, nil)
                }
            }
        }
    }
    func allCategories(id: Int, completeHandler: @escaping (Bool, [Classify]?) -> Void) {
        request = .allCategories(id: id)
        dataRequest(from: request).responseJSON { (response) in
            guard let result = response.result.value else {
                DispatchQueue.main.async {
                    completeHandler(false, nil)
                }
                return
            }
            let json = JSON(result)
            if json["status"].intValue == 200 {
                let data = json["data"].arrayValue
                var classifications = [Classify]()
                for item in data {
                    let classId = item["classId"].intValue
                    let name = item["name"].stringValue
                    let classification = Classify(name: name, classId: classId)
                    classifications.append(classification)
                }
                DispatchQueue.main.async {
                    completeHandler(true, classifications)
                }
            } else {
                DispatchQueue.main.async {
                    completeHandler(false, nil)
                }
            }
        }
    }
}
